package com.linkai.多线程._06_syn;

/**
 * @Description: synchronized 同步块，可以锁一个具体的对象
 * @Author: 林凯
 * @Date: 2021/10/19 22:12
 */
public class UnsafeBank {
    public static void main(String[] args) {
        // 账户
        Account account = new Account(100, "结婚基金");

        Drawing you = new Drawing(account, 50, "you");
        Drawing she = new Drawing(account, 100, "she");

        you.start();
        she.start();

        /*
            余额为：0
            余额为：-50
            she手里的钱100
            you手里的钱50
        * */

    }
}

// 账户
class Account {
    int money;  // 余额
    String name;    // 卡名

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

// 银行 模拟取款
class Drawing extends Thread {
    Account account;    // 账户
    // 取了多少钱
    int drawMoney;
    // 现在手里有多少钱
    int nowMoney;

    public Drawing(Account account, int drawMoney, String name) {
        super(name);
        this.account = account;
        this.drawMoney = drawMoney;
    }


    // 在这里加上 synchronized 关键字可能没有效果，因为操作的对象是 Account，而锁住 Drawing 对象是没作用的
    // synchronized 默认锁的是 this
    @Override
    public void run() {

        // 对 account 对象的操作都丢到这个块里面
        // 锁的对象就是变化的量，需要增删改的对象
        synchronized (account) {
            // 判断有没有钱
            if (account.money - drawMoney < 0) {
                System.out.println(Thread.currentThread().getName() + "钱不够，取不了");
                return;
            }

            // 模拟延时，放大问题的发生性
            try {

                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            account.money = account.money - drawMoney;
            nowMoney = nowMoney + drawMoney;

            System.out.println("余额为：" + account.money);
            System.out.println(this.getName() + "手里的钱" + nowMoney);

        }


    }
}

